package com.github.bryx.workflowweb.config.entity;

import lombok.Data;
import org.springframework.lang.NonNull;

import java.io.Serializable;

/**
 * @author zhao
 * @date 2020/1/15
 **/
@Data
public class ResultEntity<T> implements Serializable {

    public enum RESPONSE_CODE{
        SUCCESS(200),
        SERVER_ERROR(500),
        SECURITY_ERROR(403);
        int code;
        RESPONSE_CODE(int code){
            this.code = code;
        }
    }

    private static final long serialVersionUID = -1372623373646155857L;

    private T data;

    /**
     * if code is empty,the result will be convicted for failure
     * don't set code null if not necessary
     */
    private Integer code = RESPONSE_CODE.SUCCESS.code;

    private String content;

    private String errorStack;

    public void success(T data, String msg) {
        this.code = RESPONSE_CODE.SUCCESS.code;
        this.content = msg;
        this.data = data;
    }

    public void success(T data) {
        this.code = RESPONSE_CODE.SUCCESS.code;
        this.content = "请求成功";
        this.data = data;
    }

    public void failed(String msg) {
        this.code = RESPONSE_CODE.SERVER_ERROR.code;
        this.content = msg;
        this.data = null;
    }

    public void failed(RESPONSE_CODE code, String msg) {
        this.code = code.code;
        this.content = msg;
        this.data = null;
    }

    public static <T> ResultEntity<T> of(@NonNull T data) {
        ResultEntity<T> result = new ResultEntity<>();
        result.success(data);
        return result;
    }

    public static <T> ResultEntity<T> of(@NonNull RESPONSE_CODE code, @NonNull T data) {
        ResultEntity<T> result = new ResultEntity<>();
        result.success(data);
        result.setCode(code.code);
        return result;
    }

    public static <T> ResultEntity<T> ofSuccess() {
        return new ResultEntity<>();
    }

    public static <T> ResultEntity<T> ofSuccess(@NonNull String msg) {
        ResultEntity<T> result = new ResultEntity<>();
        result.success(null, msg);
        return result;
    }

    public static <T> ResultEntity<T> ofSuccess(@NonNull RESPONSE_CODE code, @NonNull String msg) {
        ResultEntity<T> result = new ResultEntity<>();
        result.failed(code, msg);
        return result;
    }

    public static <T> ResultEntity<T> ofError(@NonNull String msg) {
        ResultEntity<T> result = new ResultEntity<>();
        result.failed(msg);
        return result;
    }

    public static <T> ResultEntity<T> ofError(@NonNull RESPONSE_CODE code, @NonNull String msg) {
        ResultEntity<T> result = new ResultEntity<>();
        result.failed(code, msg);
        return result;
    }
}
